package com.lihepeng.leecode.array2.binarySearch;

import org.junit.Test;

/**
 * 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/binary-search
 * https://leetcode-cn.com/problems/binary-search/solution/er-fen-cha-zhao-xiang-jie-by-labuladong/
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Solution704 {
    public int search(int[] nums, int target) {
        int n = nums.length;
        int l = 0;
        int r = n-1;
        while (l <=r){
            int mid = l+((r-l)/2);
            if (nums[mid]>target){
                r=mid-1;
            }else if (nums[mid]<target){
                l = mid+1;
            }else {
                return mid;
            }
        }
        return -1;
    }
    @Test
    public void runTest(){
        int[] arrs = {1,2,4,5,6,8,9,10};
        int search = this.search(arrs, 2);
        System.out.println(search);
    }
}
